package com.maple.hibernate;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

public class HibernateSessionFilter implements Filter {

	public void destroy() {

	}

	@Test
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		Session session = HibernateUtil2.openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			chain.doFilter(request, response);
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			throw new RuntimeException(e);
		} finally {
			HibernateUtil2.closeAndRemoveCurrentSession();
		}

	}

	public void init(FilterConfig arg0) throws ServletException {

	}

}
